package net.alan.modules.service.impl;

import net.alan.modules.bean.Chat;
import net.alan.modules.bean.ChatItem;
import net.alan.modules.bean.PageModel;
import net.alan.modules.repository.ChatItemRepository;
import net.alan.modules.repository.ChatRepository;
import net.alan.modules.service.IChatService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Author 李岩飞
 * Email eliyanfei@126.com
 * 2017/11/21
 */
@Service
public class ChatServiceImpl extends BaseServiceImpl implements IChatService {
    private static final Logger logger = LoggerFactory.getLogger(ChatServiceImpl.class);
    @Autowired
    private ChatRepository chatRepository;
    @Autowired
    private ChatItemRepository chatItemRepository;

    @Override
    public JpaRepository getJpaRepository(Class<?> cla) {
        if (isSame(cla, Chat.class)) {
            return chatRepository;
        } else if (isSame(cla, ChatItem.class)) {
            return chatItemRepository;
        }
        return null;
    }

    @Override
    public List<Chat> findChatByUserId(Integer projectId, Integer userId) {
        return chatRepository.findByProjectIdAndUserId(projectId, userId);
    }

    @Override
    public Page<ChatItem> findChatItemByChatId(Integer chatId, PageModel pageModel) {
        return this.chatItemRepository.findByChatId(chatId, pageModel.getPageable());
    }

    @Override
    public List<Chat> listUnreadChat(Integer userId) {
        return this.chatRepository.findByUserIdAndReadedTrue(userId);
    }

    @Override
    public Chat getOtherChat(Integer projectId, Integer userId, Integer toUserId) {
        return this.chatRepository.findByProjectIdAndUserIdAndToUserId(projectId, userId, toUserId);
    }

    @Override
    public void deleteChatByUserId(Integer projectId, Integer userId) {
        this.chatRepository.deleteByProjectIdAndUserId(projectId, userId);
    }
}
